package com.test.gpa.security.filter;

import com.alibaba.fastjson.JSON;
import com.test.gpa.security.Impl.LoginUser;
import com.test.gpa.security.config.RedisCache;
import com.test.gpa.security.config.ResponseResult;
import com.test.gpa.security.util.JwtUtil;
import com.test.gpa.security.util.WebUtils;
import io.jsonwebtoken.Claims;
import nl.basjes.shaded.org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token效验解析
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {
        //获取token
        String token="";
        token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法,加密方式不同");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "用户未登录");
            String jsonString = JSON.toJSONString(result);
            WebUtils.renderString(response, jsonString);
            return;
        }
        //存入SecurityContextHolder    安全上下文
//           使用了ThreadLocal 只要针对某个使用者的逻辑执行都是在同一个线程中进行，
//            即使不在各个方法之间以参数的形式传递其安全上下文，
//            各个方法也能通过SecurityContextHolder工具获取到该安全上下文。
        //只能保证在同一请求中安全 不同的请求不在同一个线程内
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
